package com.zt.sso.interceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.springframework.web.servlet.handler.HandlerInterceptorAdapter;
import com.zt.sso.util.SsoCheck;

public class SsoInterceptor extends HandlerInterceptorAdapter {
	
	@Override
	public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler)
			throws Exception {
		//登陆相关url直接放行
		String url = request.getPathInfo();
		if(url.contains("login")) {  
	        return true;  
	    } 
		boolean aflag = false;
		 String userId = SsoCheck.getCookiesValues(request, response, "userId");
	     String token = SsoCheck.getCookiesValues(request, response, "token");
	     String userType = SsoCheck.getCookiesValues(request, response, "userType");
	     String authMsg = "";
	     if(null != token && null != userId){
		    	//验证登录有效性
	    		if(SsoCheck.checkToken(userId, userType, token)){
		    		aflag = true;
		    	}else{
		    		authMsg = "无效用户,请重新登录";
		    		aflag = false;
		    	}
		    	
		    }else{
		    	authMsg = "尚未登录";
	    		aflag = false;
		    }
	     	if(!aflag){
	     		request.setAttribute("msg", authMsg);
	     		request.getRequestDispatcher("login").forward(request, response);
	     	}
			return aflag;

	}

}
